import { isValidIP, isValidPort } from "./utils.js";
const localIP = document.querySelector("#local-ip");
const localPort = document.querySelector("#local-port");
const statusText = document.querySelector(".status-bar .status");
const progressDesc = document.querySelector("#progress-desc");
const progressPercent = document.querySelector("#progress-percent");
const progressBar = document.querySelector(".progress-bar");
const photoWall = document.querySelector(".photo-wall");
const leftBtn = document.querySelector(".left-btn");
const rightBtn = document.querySelector(".right-btn");
// canvas初始化
const canvas = document.querySelector("#preview");
const ctx = canvas.getContext("2d");
const width = (canvas.width = 800);
const height = (canvas.height = 600);
// 用于存储文件名和当前预览的图片
let cur = 0;
let imageNameList = [];

let isReady = false;
//连接WebSocket
fetch("/local-ip")
  .then((res) => res.json())
  .then((data) => {
    localIP.value = data.ip;
    localPort.value = 3004;
    const socket = new WebSocket(
      `ws://${localIP.value}:${localPort.value}/msg`
    );
    socket.addEventListener("message", wsHandler);
  });

function wsHandler(e) {
  console.log("Message from server ", e.data);
  // 命令处理
  const cmdArgs = e.data.split(" ");
  switch (cmdArgs[0]) {
    case "show":
      fetchInput();
      statusText.classList.add("ready");
      statusText.textContent = "已收到输入图像";
      progressPercent.textContent = "0%";
      progressBar.style.width = "0%";
      progressDesc.textContent = "";
      leftBtn.classList.add("visually-hidden");
      rightBtn.classList.add("visually-hidden");
      ctx.clearRect(0, 0, width, height);
      progressDesc.textContent = "识别算法正在初始化...";
      break;
    case "progress":
      if (cmdArgs[1] !== "done") {
        progressDesc.textContent = "图像识别中...";
        progressBar.style.width = `${cmdArgs[1]}%`;
        progressPercent.textContent = `${cmdArgs[1]}%`;
        isReady = true;
      } else {
        progressDesc.textContent = "图像识别完成";
        leftBtn.classList.remove("visually-hidden");
        rightBtn.classList.remove("visually-hidden");
        isReady = true;
        displayResult(imageNameList[cur]);
      }
      break;
  }
}

// 获取照片墙
function fetchInput() {
  while (photoWall.hasChildNodes()) {
    photoWall.removeChild(photoWall.firstChild);
  }
  console.log("道者了");
  fetch("/input")
    .then((res) => res.json())
    .then((data) => {
      imageNameList = data;
      for (let i = 0; i < data.length; i++) {
        const img = document.createElement("img");
        img.src = `/input/${data[i]}?time=${new Date().getTime()}`;
        img.alt = String(i);
        photoWall.appendChild(img);
      }
    });
}

// 展示识别结果
function displayResult(imgName) {
  const image = new Image();
  image.onload = () => {
    ctx.clearRect(0, 0, width, height);
    ctx.drawImage(image, 0, 0, width, height);
  };
  image.src = `/output/${imgName}`;
}

// 切换照片墙的图片
function updateWall(newIndex) {
  const children = photoWall.childNodes;
  children[cur].classList.remove("active");
  children[newIndex].classList.add("active");
  displayResult(imageNameList[newIndex]);
  cur = newIndex;
}

// 点击图片
photoWall.addEventListener("click", (e) => {
  if (e.target.alt) {
    updateWall(Number(e.target.alt));
  }
});

leftBtn.addEventListener("click", () => {
  updateWall((cur - 1) % imageNameList.length);
});
rightBtn.addEventListener("click", () => {
  updateWall((cur + 1) % imageNameList.length);
});
